<template>
  <div class="page-container">
    <!-- 头部搜索 -->
    <div class="cage-header">
      <el-card class="box-card">
        <div class="cage-header-left">
          <span class="label">笼子名称：</span>
          <el-input
            placeholder="请输入内容"
            v-model="searchConcent"
            clearable
            class="search-input"
          >
          </el-input>
          <el-button type="success" class="search-btn" @click="search"
            >搜索</el-button
          >
        </div>
        <div class="cage-header-right">
          <el-button type="success" class="add-btn" @click="addCage"
            >新增笼子</el-button
          >
        </div>
      </el-card>
    </div>
    <!-- 中间表格 -->
    <div class="cage-content">
      <el-card class="box-card">
        <!-- 表格及分页器 -->
        <TemplateTable
          class="table-box"
          :tableData="tableData"
          :columns="columns"
          :pageNum="pageNum"
          :pageSize="pageSize"
          :total="pageTotal"
          @currentPageChange="currentChange"
          @pageSizeChange="handleSizeChange"
        >
          <template #operation="{ row }">
            <el-button
              @click="handleDetail(row)"
              type="success"
              size="small"
              round
              icon="el-icon-view"
              >笼子管理</el-button
            >

            <el-button
              type="danger"
              size="small"
              round
              icon="el-icon-delete"
              @click="handleDelete(row)"
              >删除</el-button
            >
          </template>
        </TemplateTable>
      </el-card>
    </div>
    <!-- 新增笼子弹窗 -->
    <el-dialog title="新增笼子" :visible.sync="addCageDialog" width="30%">
      <el-form
        ref="addCageForm"
        :rules="addCageRules"
        :model="form"
        label-width="80px"
      >
        <el-form-item label="笼子名字" prop="cageName">
          <el-input v-model="form.cageName"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addCageDialog = false">取 消</el-button>
        <el-button type="primary" @click="addCageDialogConfirm('addCageForm')"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import TemplateTable from "@/components/template-table"

export default {
  name: "cage-manage",
  components: {
    TemplateTable
  },
  data() {
    return {
      searchConcent: "", //当前搜索内容
      pageNum: 1,
      pageSize: 10,
      pageTotal: 0,
      addCageDialog: false, //新增笼子弹窗
      tableData: [],
      form: {
        cageName: ""
      },
      addCageRules: {
        name: [{ required: true, message: "请输入笼子名字", trigger: "blur" }]
      }
    }
  },
  created() {
    this.init()
  },
  computed: {
    columns() {
      return [
        {
          propName: "name",
          label: "笼子名称",
          width: 100
        },
        {
          propName: "createdTime",
          label: "新增时间"
        },
        {
          propName: "",
          label: "操作",
          width: "300",
          slotName: "operation"
        }
      ]
    }
  },
  methods: {
    currentChange(pageNum) {
      this.pageNum = pageNum
      this.loadData()
    },
    handleSizeChange(size) {
      this.pageSize = size
      this.loadData()
    },
    search() {
      this.pageNum = 1
      this.loadData()
    },
    init() {
      this.searchConcent = ""
      this.pageNum = 1
      this.pageSize = 10
      this.loadData()
    },
    //加载笼子列表数据
    async loadData() {
      const that = this
      let params = {
        pageNumber: that.pageNum,
        pageSize: that.pageSize,
        yardId: localStorage.getItem("yardId") || 1,
        cageName: that.searchConcent
      }
      try {
        let res = await that.$http.get("/cage/cages", params)
        res.data.content.forEach(item => {
          item.createdTime = that
            .$moment(item.createdTime)
            .format("YYYY-MM-DD hh:mm:ss")
        })
        that.tableData = res.data.content
        that.pageTotal = res.data.totalElements
      } catch (err) {
        console.log("报错了：", err)
      }
    },
    //点击详情，查看笼子中的宠物列表
    handleDetail(row) {
      console.log("点击详情", row)
      this.$router.push({
        path: "/cage-manage/cage-detail",
        query: {
          cageNum: row.id,
          openType: "1"
        }
      })
    },
    //删除笼子
    handleDelete(row) {
      const that = this
      this.$confirm(
        "此操作将永久删除该笼子, 请先确认该笼内宠物为空。是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      )
        .then(() => {
          let params = {
            cageId: row.id
          }
          that.$http
            .delete("/cage/deleteCage", params)
            .then(res => {
              if (res.code === 0) {
                that.$message({
                  message: "删除笼子成功",
                  type: "success"
                })
                that.loadData()
              }
            })
            .catch(err => {
              console.log(err)
            })
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          })
        })
    },
    //打开新增笼子弹窗
    addCage() {
      this.form.cageName = ""
      this.addCageDialog = true
    },
    //确认新增笼子
    addCageDialogConfirm(formName) {
      this.$refs[formName].validate(async valid => {
        if (valid) {
          let params = {
            cageName: this.form.cageName,
            yardId: localStorage.getItem("yardId") || 1 //因为登录还差session,所以这里本地先不登陆，未存储yardId
          }
          try {
            await this.$http.post("/cage/newCage", params)
            this.$message({
              message: "新增笼子成功",
              type: "success"
            })
            this.loadData()
            this.addCageDialog = false
          } catch (err) {
            console.log("报错了：", err)
          }
        } else {
          console.log("error submit!!")
          return false
        }
      })
    }
  }
}
</script>

<style scoped lang="scss">
.page-container {
  .cage-header /deep/.el-card__body {
    display: flex;
    justify-content: space-between;
    .cage-header-left {
      display: flex;
      justify-content: flex-start;
      .label {
        width: 100px;
        line-height: 40px;
      }
      .search-input {
        width: 200px;
        margin-right: 10px;
      }
    }
  }
  //表格区域样式
  .cage-content {
    margin-top: 40px;
    .el-pagination {
      text-align: right;
    }
  }
}
</style>
